package com.cat.dynamicPlanning;

import java.util.Arrays;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/maximum-length-of-pair-chain/
 * @create 2025/9/4 19:06
 * @since JDK17
 */

public class Solution68 {
    int cnt, n;
    int[] ends;
    int f(int t, int n) {
        if (n == 0) {
            return n;
        }
        int l = -1, r = n, mid;
        while (l + 1 < r) {
            mid = l + r >> 1;
            if (ends[mid] >= t) {
                r = mid;
            } else {
                l = mid;
            }
        }

        return r;
    }

    public int findLongestChain(int[][] pairs) {
        n = pairs.length;
        ends = new int[n];
        Arrays.sort(pairs, (a, b) -> a[0] - b[0]);
        for (int i = 0; i < n; i++) {
            int j = f(pairs[i][0], cnt);
            if (j == cnt) {
                ends[cnt++] = pairs[i][1];
            } else {
                ends[j] = Math.min(ends[j], pairs[i][1]);
            }
        }

        return cnt;
    }
}
